package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 商品三级分类列表用树树形结构封装返回
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1, 查出所有分类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);

        // 2, 组装成父子结构的树形结构
        // 先找到所有的一级分类
        List<CategoryEntity> levelMenus = categoryEntityList.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildren(menu, categoryEntityList));
                    return menu;
                }).sorted(Comparator.comparingInt(menu -> ((menu.getSort()) == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
        return levelMenus;
    }

    @Override
    public Boolean removeCategoryByIds(List<Long> catIds) {
        // todo: 检查当前删除的菜单,是否被别的地方占用
        int ids = baseMapper.deleteBatchIds(catIds);
        return ids > 0;
    }

    /**
     * 找到catelogId的完整路径
     * [父/子/孙]  完成路径,[2, 34, 225]
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPaths = this.findParentPath(catelogId, paths);
        Long[] array = parentPaths.toArray(new Long[parentPaths.size()]);
        return array;
    }

    /**
     * // 修改 更新数据,并级联更新
     *
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        // 更新自己表
        this.updateById(category);
        // 更新品牌分类关联表
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        paths.add(catelogId);
        return paths;
    }

    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        return all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
    }


}
